<?php

if( !defined('CORE_PATH') ) die("Access Denied");

kan_import( array('PageManager','ThemeManager') );

class SitesManager extends Manager {

    protected $models = array("Site","Theme","Image","Banner","Advert","DownloadCategory","MediaCategory","FeedbackCategory","Spotlight");
    protected $helpers = array("HTML","Cache");
    
    public function __construct() {
        parent::__construct('sites');
        $this->setItemClassName('Site');
    }

    public function getAllSites() {
        return $this->getItems(0, NULL, array(
            'order' => array("SiteName ASC")
        ));
    }

    public function getSites($start = 0, $limit = NULL, $options = NULL) {
        $dOptions = array( 'order' => array("SiteName ASC") );

        if($options != NULL) {
            $dOptions = array_merge($dOptions, $options);
        }

        return $this->getItems($start, $limit, $dOptions);
    }

    public function getSite($siteid) {
        
        $site = $this->Site->findFirst(array(
            'filter' => array(
                'OR' => array(
                    'id' => $siteid,
                    'SiteIdentifier' => $siteid
                )
            )
        ));
        
		
        // initialize the theme object
        if( $site ) {
            $theme = $site->getTheme();
        }
        
        return $site;
    }
    
    public function findSite($options = NULL) {
        return $this->Site->find($options);
    }

    public function createNewSite() {

        if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }

        if (!isset($_POST['SiteIdentifier'])) {
            return false;
        }
        
        $site = new Site(array(
            'SiteIdentifier' => $_POST['SiteIdentifier'],
            'SiteType' => $_POST['SiteType'],
            'SiteName' => $_POST['SiteName'],
            'SiteDomain' => $_POST['SiteDomain'],
            'SiteEmail' => $_POST['SiteEmail'],
            'SiteAddress' => $_POST['SiteAddress'],
            'SitePhone' => $_POST['SitePhone'],
            'SiteDescription' => $_POST['SiteDescription'],
            'SiteCMSLogo' => $_POST['SiteCMSLogo'],
            'SiteLogo' => $_POST['SiteLogo'],
            'SiteSlogan' => $_POST['SiteSlogan'],
            'SiteKeywords' => $_POST['SiteKeywords'],
            'SiteHomePageText' => $_POST['SiteHomePageText'],
            'SiteFooterText' => $_POST['SiteFooterText'],
            'SiteThemeID' => $_POST['SiteThemeID'],
            'SiteThemeCSSID' => $_POST['SiteThemeCSSID'],
            'SiteFavicon' => $_POST['SiteFavicon']
        ));
        
        $site->save();

        $newSiteID = $site->getId();
        
        $feedbackCategory = new FeedbackCategory(array(
            'SiteID' => $site->getId(),
            'CategoryName' => 'General',
            'CategoryTag' => 'general',
            'CategoryDesc' => 'General Feedback',
            'DateCreated' => date('Y-m-d')
        ));
        $feedbackCategory->save();

        // article categories
        $articleCategory = new ArticleCategory(array(
            'SiteID' => $site->getId(),
            'CategoryName' => "News",
            "CategoryAlias" => "news",
            "CategoryDescription" => "News Articles"
        ));
        $articleCategory->save();
        
        $articleCategory = new ArticleCategory(array(
            'SiteID' => $site->getId(),
            'CategoryName' => "Blog",
            "CategoryAlias" => "blog",
            "CategoryDescription" => "Blog Articles"
        ));
        $articleCategory->save();

        // download categories
        $downloadCategory = new DownloadCategory(array(
            'SiteID' => $site->getId(),
            'CategoryName' => "General",
            "CategoryAlias" => "general",
            "CategoryDescription" => "General Downloads"
        ));
        $articleCategory->save();

        // event categories
        $eventCategory = new EventCategory(array(
            'SiteID' => $site->getId(),
            'Category' => "General",
            "CategoryAlias" => "general",
            "CategoryDescription" => "General Events"
        ));
        $eventCategory->save();

        // quick links categories
        $linkCategory = new LinkCategory(array(
            'SiteID' => $site->getId(),
            'CategoryName' => "General",
            "CategoryDescription" => "General Events"
        ));
        $linkCategory->save();

        // return true to indicate all executed successfully
        return true;
    }

    public function updateSite() {
        if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }
        
        $site = new Site(array(
            'id' => $_POST['id'],
            'SiteIdentifier' => $_POST['SiteIdentifier'],
            'SiteType' => $_POST['SiteType'],
            'SiteName' => $_POST['SiteName'],
            'SiteDomain' => $_POST['SiteDomain'],
            'SiteEmail' => $_POST['SiteEmail'],
            'SiteAddress' => $_POST['SiteAddress'],
            'SitePhone' => $_POST['SitePhone'],
            'SiteDescription' => $_POST['SiteDescription'],
            'SiteCMSLogo' => $_POST['SiteCMSLogo'],
            'SiteLogo' => $_POST['SiteLogo'],
            'SiteSlogan' => $_POST['SiteSlogan'],
            'SiteKeywords' => $_POST['SiteKeywords'],
            'SiteHomePageText' => $_POST['SiteHomePageText'],
            'SiteFooterText' => $_POST['SiteFooterText'],
            'SiteThemeID' => $_POST['SiteThemeID'],
            'SiteThemeCSSID' => $_POST['SiteThemeCSSID'],
            'SiteFavicon' => $_POST['SiteFavicon']
        ));
        
        $site->save();

        $this->Cache->clearCache($_POST['SiteIdentifier']);
    }

    public function updateSiteHomePageContent() {
        if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }
		
		$site = new Site( array(
			'id' => $_POST['id'],
			'SiteHomePageText' => $_POST['SiteHomePageText']
		));
		$site->save();
		
		return $site;
    }

    public function updateSiteFooterContent() {
        if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }
		
		$site = new Site( array(
			'id' => $_POST['id'],
			'SiteFooterText' => $_POST['SiteFooterText']
		));
		$site->save();
		
		return $site;
    }
    
    /**
     * Clears the Cache of the site with the specified ID
     *
     * @param int $siteid the database record ID of the site
     */
    public function clearSiteCache($siteid) {
         if( !is_array($siteid) ) {
             $siteid = array($siteid);
         }
         
         foreach($siteid as $id) {
            // get a Site object to work with
            $site = $this->getSite($id);

            // clear the system cache
            if( $site ) $this->Cache->clearCache($site->getSiteIdentifier());
         }
        
    }

    /**
     * Deletes a Site from the KAN system and clears the site cache as well
     *
     * @param int $siteid the database record ID of the site
     */
    public function deleteSite($siteid) {
        
        // get a Site object to work with
        $site = $this->getSite($siteid);

        // clear the system cache
        $this->Cache->clearCache($site->getSiteIdentifier());

        // before we proceed to delete the site information, we first need
        // to clear all related documents from the server first
        // first images
        $this->Image->deleteAll(array('SiteID' => $siteid));
        // then banners
        //$this->deleteSiteBanners($site->getSiteID());
        // then adverts
        //$this->deleteSiteAdverts($site->getSiteID());
        // then media
        $this->MediaCategory->deleteAll(array('SiteID' => $siteid));
        // then spotlights
        $this->Spotlight->deleteAll(array('SiteID' => $siteid));
        // then downloads
        $this->DownloadCategory->deleteAll(array('SiteID' => $siteid));

        // delete the site itself
        $site->delete();
    }

    public function getSiteLinksArray($siteid) {

        $site = $this->getSite($siteid);

        // generate links for the CMS section of the site
        $cms_quick_links = array(
            'group_title' => 'CMS Quick Links',
            'links' => array(
                array('title' => 'CMS Home', 'href' => '../pages/index.php?goto=../cms/index.php')
            )
        );

        // generate the links to all the KAN sites
        $sites = $this->getAllSites();
        $links_array = array();
        for ($i = 0; $i < count($sites); $i++) {
            $siteEl = $sites[$i];
            array_push($links_array, array('title' => $siteEl->getSiteName(), 'href' => $siteEl->getHomePageURL()));
        }

        // create the data group for the sites links
        $cms_sites = array(
            'group_title' => 'Sites',
            'links' => $links_array
        );


        // generate links for common kan areas
        $tag = $site->getSiteIdentifier();

        $common_kan_links = array(
            'group_title' => 'Predefined Links',
            'links' => array(
                array('title' => 'Home Page', 'href' => $site->getPageURL('index')), 
                array('title' => 'Articles', 'href' => $site->getPageURL('articles')), 
                array('title' => 'Upcoming Events', 'href' => $site->getPageURL('events')), 
                array('title' => 'Downloads', 'href' => $site->getPageURL('downloads')), 
                array('title' => 'Media', 'href' => $site->getPageURL('media')), 
                array('title' => 'Gallery', 'href' => $site->getPageURL('gallery'))
            )
        );



        // generate the links used in the Quick Links Section
        $ql_array = array();
        $lm = new LinksManager();
        $links = $lm->getLinks();

        foreach($links as $link) {
            array_push($ql_array, array('title' => $link->getName(), 'href' => $link->getURL()));
        }

        $site_quick_links = array(
            'group_title' => 'Quick Links',
            'links' => $ql_array
        );

        // add the article category links
        $arts = new ArticlesManager();
        $categories = $arts->getArticleCategories();
        $article_cats = array();

        foreach ($categories as $cat) {
            array_push($article_cats, array('title' => $cat->getCategoryName(), 'href' => $cat->getURL()));
        }

        $cms_articles = array(
            'group_title' => 'Article Categories',
            'links' => $article_cats
        );

        // add the pages links
        $pm = new PageManager();
        $nodes = $pm->getAdjacencyTree()->getFullNodes(
                array("id", "SiteID", "PageName", "PageNameAlias", "PageType", "PagePath", "RedirectURL", "Published")
        );
        $cms_page_list = array();
        $this->processPages($cms_page_list, $nodes);
        $cms_pages = array(
            'group_title' => 'Site Pages',
            'links' => $cms_page_list
        );

        // create the final list of link arrays in the preferred order
        $link_array = array(
            $cms_sites,
            //$current_site,
            $common_kan_links,
            $cms_pages,
            $cms_articles,
            $site_quick_links,
            $cms_quick_links
        );

        return $link_array;
    }

    private function processPages(&$pages_array, $nodes, $depth = 0) {
        $currentDepth = $depth;

        foreach ($nodes as $data) {
            $page = new Page($data);

            $name = str_repeat("&nbsp; ", $depth) . $page->getName();
            $url = $page->getURL();

            array_push($pages_array, array('title' => $name, 'href' => $url));

            if (isset($data['children'])) {
                $this->processPages($pages_array, $data['children'], ++$depth);
            }

            $depth = $currentDepth;
        }
    }

    /**
     * Sets the site with the supplied database record ID as the default site in the systetem
     */
    public function setSiteAsDefault($siteid) {
        $this->Site->updateAll( array('SiteType' => 'sub'));
        $this->Site->updateAll( array('SiteType' => 'main'), array('id' => $siteid));
    }

    /**
     * Sets the site with the supplied database record ID as the default site in the systetem
	 *
	 * @param mixed $siteid array or int representing the Sites to be updated
	 * @param int $status 1 or 0 representing the active state
     */
    public function setSiteAsActive($siteid, $status) {

		if (!defined("IN_CMS") || !IN_CMS) {
            return;
        }
        
        $this->Site->updateAll(array('SiteActive' => $status), array("id IN" => implode(",", $siteid)));
    }

    private function deleteFile($file) {
        if ($file != "none" && $file != "" && $file != '.' && $file != '..') {
            if (file_exists($file)) {
                try {
                    unlink($file);
                } catch (Exception $e) {
                    echo $e;
                }
            }
        }
    }

    /*private function deleteSiteBanners($siteID) {

        $db = $this->getDatabase();

        $selectSQL = sprintf("SELECT * FROM banner_images WHERE SiteID = %s", $db->sanitizeInput($siteID, "int"));
        $imageResult = mysql_query($selectSQL) or die(mysql_error());

        // if there are no images to delete, simply exit the procedure
        if (mysql_num_rows($imageResult) == 0) {
            mysql_free_result($imageResult);
            return;
        }

        while ($images = mysql_fetch_assoc($imageResult)) {
            $media = $images['BannerPath'];

            $this->deleteFile("../" . $media);
        }

        mysql_free_result($imageResult);
    }

    private function deleteSiteAdverts($siteID) {

        $db = $this->getDatabase();

        $selectSQL = sprintf("SELECT * FROM advert_images WHERE SiteID = %s", $db->sanitizeInput($siteID, "int"));
        $imageResult = mysql_query($selectSQL) or die(mysql_error());

        // if there are no images to delete, simply exit the procedure
        if (mysql_num_rows($imageResult) == 0) {
            mysql_free_result($imageResult);
            return;
        }

        while ($images = mysql_fetch_assoc($imageResult)) {
            $media = $images['AdvertPath'];

            $this->deleteFile("../" . $media);
        }

        mysql_free_result($imageResult);
    }*/
}

?>